import paho.mqtt.client as mqtt
import json
import time
import random

# MQTT配置
MQTT_BROKER = "localhost"  # MQTT服务器地址
MQTT_PORT = 1883          # MQTT端口
DEVICE_ID = "device001"   # 设备ID

# 创建MQTT客户端
client = mqtt.Client()

# 连接到MQTT服务器
client.connect(MQTT_BROKER, MQTT_PORT)

# 发送设备数据
def send_device_data():
    data = {
        "temperature": round(random.uniform(20, 30), 2),  # 模拟温度数据
        "humidity": round(random.uniform(40, 60), 2)      # 模拟湿度数据
    }
    topic = f"device/{DEVICE_ID}/data"
    client.publish(topic, json.dumps(data))
    print(f"发送数据: {data}")

# 发送心跳包
def send_heartbeat():
    topic = f"device/{DEVICE_ID}/heartbeat"
    client.publish(topic, "")
    print("发送心跳包")

# 发送设备状态
def send_status(status):
    data = {
        "status": status  # "online" 或 "offline"
    }
    topic = f"device/{DEVICE_ID}/status"
    client.publish(topic, json.dumps(data))
    print(f"发送状态: {status}")

# 主循环
try:
    # 发送在线状态
    send_status("online")
    
    while True:
        # 每5秒发送一次设备数据
        send_device_data()
        # 每30秒发送一次心跳包
        send_heartbeat()
        time.sleep(5)
        
except KeyboardInterrupt:
    # 发送离线状态
    send_status("offline")
    client.disconnect()